package com.zzz.web.LocationAlgo;

import com.zzz.web.DB.GetContext;
import com.zzz.web.DB.operationOnDataBase;
import com.zzz.web.Data.NewRssiList;
import com.zzz.web.Data.RSSI;
import com.zzz.web.Data.XYaxis;
import com.zzz.web.Data.validityRSSI;
import com.zzz.web.service.RssiService;
import com.zzz.web.tools.tool;
import org.junit.Test;
import org.springframework.context.ApplicationContext;

import java.beans.FeatureDescriptor;
import java.util.ArrayList;
import java.util.List;

/**
 * 单例类update专门用于更新数据
 */
public class Update {
    //点的总数
    int SUMPOINTS = 30;
    int counter = 30;
    //两个list 一个用来保存rssi数据，另一个用来保存当前rssi数据已经保存了几个
    List<NewRssiList> tempRssis = new ArrayList<>(SUMPOINTS);

//    NewRssiList[] tempRssis = new NewRssiList[SUMPOINTS];

    public static Update update;


    //初始化
    private Update() {
        ApplicationContext context = GetContext.getContext();
        List<RSSI> allService = context.getBean("rssiService", RssiService.class).all();
        for (int i = 0; i < SUMPOINTS; i++) {
            NewRssiList newRssiList = new NewRssiList();
            newRssiList.featureRSSI = allService.get(i);
            tempRssis.add(newRssiList);
        }
    }

    //设置单例类
    public static Update getInstance() {
        if (update == null) {
            update = new Update();
        }
        return update;
    }

    //主要方法，更新数据
    public void updataRSSI(validityRSSI validityRSSI) {
        for (int i = 0; i < SUMPOINTS; i++) {
            if (tool.isClose(tempRssis.get(i).featureRSSI,validityRSSI.getRssi())) {
                validityRSSI.getRssi().setNumber(i + 1);
                ArrayList<RSSI> list = tempRssis.get(i).list;
                list.add(validityRSSI.getRssi());

                if (list.size() >= 30){
                    updateInDB update = new updateInDB(list);
                    Thread thread = new Thread(update);
                    thread.start();
                    list.clear();
                    return;
                }
            }
        }

        NewRssiList newRssiList = new NewRssiList();
        newRssiList.list.add(validityRSSI.getRssi());
        newRssiList.featureRSSI = validityRSSI.getRssi();

        tempRssis.add(newRssiList);
        SUMPOINTS++;
    }

    //更新数据线程设置
    class updateInDB implements Runnable {
        List<RSSI> rssis;

        public updateInDB(List<RSSI> rssis) {
            this.rssis = rssis;
        }

        @Override
        public void run() {

            RSSI kmeansRSSI = K_Means.kmeans(rssis);
            new operationOnDataBase().insertIntoData(kmeansRSSI);

        }
    }

}
